package com.mszlu.rpc.spring;

import com.mszlu.rpc.annontation.MsReference;
import com.mszlu.rpc.annontation.MsService;
import com.mszlu.rpc.proxy.MsRpcClientProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;

/**
 * 在SpringBean的初始化前后进行调用，一般代码都写到初始化后
 */

public class MsRpcSpringBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 找到MsService注解，以及MsReference注解
        // bean代表所有能扫描到的Bean

        System.out.println("postProcessAfterInitialization: "+bean);
        if(bean.getClass().isAnnotationPresent(MsService.class)){
            MsService msService = bean.getClass().getAnnotation(MsService.class);
            //  加了MsService的bean被找到了，就把其中的方法 发布为服务
        }

        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            MsReference msReference = declaredField.getAnnotation(MsReference.class);
            if(msReference != null){
                // 找到了MsReference的字段，生成相应的代理类，当接口方法调用的时候，实际上是访问代理类的invoke方法
                MsRpcClientProxy msRpcClientProxy = new MsRpcClientProxy();
                Object proxy = msRpcClientProxy.getProxy(declaredField.getType());
                // 允许通过访问字段  将代理对象注入
                declaredField.setAccessible(true);
                try {
                    declaredField.set(bean,proxy);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return bean;
    }


}
